layui.use(['element', 'layer', 'form'], function() {
    var element = layui.element;
    var layer = layui.layer;
    var form = layui.form;

    $.ajax({
        type: "GET",
        url: "user/info",
        dataType: "json",
        headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
        success: function (result) {
            if (result.code == 0) {
                var user = result.data;
                form.val("emailForm", {"nickName": user.nickName, "email": user.email});
                form.val("settingForm", {"searchStyle": user.searchStyle, "favoriteLink": user.favoriteLink, "smartAi": user.smartAi});
            }
        }
    });

    form.on('switch(searchStyleSwitch)', function(data){
      layer.load();
      var searchStyle = data.elem.checked? 1 : 0;
      $.ajax({
          type: "POST",
          url: "user/setting",
          data: JSON.stringify({"searchStyle": searchStyle}),
          contentType: 'application/json;charset=utf-8',
          dataType: "json",
          headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
          success: function (result) {
              layer.closeAll('loading');
              if (result.code == 0) {
                  layer.msg("操作成功", {icon: 6});
                  if(searchStyle == 1){
                    $("#searchDiv", parent.document).addClass("bookmark");
                  }else{
                    $("#searchDiv", parent.document).removeClass("bookmark");
                  }
              } else {
                  layer.msg(result.msg, {icon: 5});
              }
          }
      });
    });

    form.on('switch(favoriteLinkSwitch)', function(data){
      layer.load();
      var favoriteLink = data.elem.checked? 1 : 0;
      $.ajax({
          type: "POST",
          url: "user/setting",
          data: JSON.stringify({"favoriteLink": favoriteLink}),
          contentType: 'application/json;charset=utf-8',
          dataType: "json",
          headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
          success: function (result) {
              layer.closeAll('loading');
              if (result.code == 0) {
                  layer.msg("操作成功", {icon: 6});
              } else {
                  layer.msg(result.msg, {icon: 5});
              }
          }
      });
    });

    form.on('switch(smartAiSwitch)', function(data){
      layer.tips('该功能暂未开放', data.othis, {tips: 3});
      form.val("settingForm", {"smartAi": 0});
    });

    $("#resetSort").click(function(){
        layer.confirm('确认重置吗？', function(index){
            layer.close(index);

            layer.load();
            $.ajax({
                type: "POST",
                url: "user/resetSort",
                dataType: "json",
                headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                success: function (result) {
                    layer.closeAll('loading');
                    if (result.code == 0) {
                        layer.msg("操作成功", {icon: 6});
                    } else {
                        layer.msg(result.msg, {icon: 5});
                    }
                }
            });
        });
    });

    // 修改邮箱
    form.on('submit(updateEmail)', function (data) {
        layer.load();
        $.ajax({
            type: "POST",
            url: "user/update",
            data: JSON.stringify(data.field),
            contentType: 'application/json;charset=utf-8',
            dataType: "json",
            headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
            success: function (result) {
                layer.closeAll('loading');
                if (result.code == 0) {
                    layer.msg("保存成功", {icon: 6});
                } else {
                    layer.msg(result.msg, {icon: 5});
                }
            }
        });
        return false;
    });

    // 修改密码
    form.on('submit(updatePassword)', function (data) {
        layer.load();
        $.ajax({
            type: "POST",
            url: "user/password",
            data: {"newPassword":md5(data.field.newPassword),"code":data.field.code},
            dataType: "json",
            headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
            success: function (result) {
                layer.closeAll('loading');
                if (result.code == 0) {
                    layer.msg('保存成功', {icon: 6, time: 1000}, function(){
                        localStorage.clear();
                        parent.window.location.href = "login.html";
                    });
                } else {
                    layer.msg(result.msg, {icon: 5});
                }
            }
        });
        return false;
    });

    form.verify({
        password: function (value, item) {
            if(value.length<6||value.length>16){
                return '输入6~16个字符，区分大小写';
            }
        },
        nickname: function (value, item) {
          var msg;
          $.ajax({
              type: "GET",
              url: 'user/nickname/check/' + value,
              async: false,
              dataType: 'json',
              headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
              success: function (result) {
                  if (result.data) {
                      msg = "昵称已被使用";
                  }
              }
          });
          return msg;
        }
    });

    // 验证强度
    $("#newPassword").keyup(function(){
         $("#pwdValid").css("display","flex");
         var val = $(this).val();
         var lvTxt = ['', '低', '中', '高'];
         var lv = 0;
         if (val.match(/[a-z]/g)) { lv++; } //验证是否包含字母
         if (val.match(/[0-9]/g)) { lv++; } // 验证是否包含数字
         if (val.match(/(.[^a-z0-9])/g)) { lv++; } //验证是否包含字母，数字，字符
         if (val.length < 6) { lv = 0; } //如果密码长度小于6位，提示消息为空
         if (lv > 3) { lv = 3; }

         $("#pwdValid").find("span").each(function(index){
            if(index < lv) {
                $(this).addClass("active");
            }else{
                $(this).removeClass("active");
            }
         });
         $("#pwdValid").find(".name").text(lvTxt[lv]);
    });

    // 发送验证码
    window.sendEmailCode = function (obj) {
        var email = $("#email").val();
        var reg = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        if(email.match(reg)){
            obj.setAttribute("disabled", true);
            obj.value="重试(60)";
            // 倒计时
            var countdown = 59;
            var interval = setInterval(function() {
                if (countdown == 0) {
                    obj.removeAttribute("disabled");
                    obj.value="点击获取";
                    countdown = 59;
                    clearInterval(interval);
                } else {
                    obj.setAttribute("disabled", true);
                    obj.value="重试(" + countdown + ")";
                    countdown--;
                }
            }, 1000);
            // 请求后台
            $.ajax({
                type: "GET",
                url: "user/email/code",
                headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
                data: {"email": email}
            });
        }else{
            $("#email").focus().addClass("layui-form-danger");
            layer.msg('邮箱格式不正确', {icon: 5, anim: 6});
        }
    };

    // 发送验证码
    window.validEmail = function (obj) {
        var newPassword = $("#newPassword").val();
        if(newPassword == ""){
            $("#newPassword").focus().addClass("layui-form-danger");
            layer.msg('请输入新密码', {icon: 5, anim: 6});
            return false;
        }
        obj.setAttribute("disabled", true);
        obj.value="重试(60)";
        // 倒计时
        var countdown = 59;
        var interval = setInterval(function() {
            if (countdown == 0) {
                obj.removeAttribute("disabled");
                obj.value="点击邮箱验证";
                countdown = 59;
                clearInterval(interval);
            } else {
                obj.setAttribute("disabled", true);
                obj.value="重试(" + countdown + ")";
                countdown--;
            }
        }, 1000);
        // 请求后台
        $.ajax({
            type: "GET",
            url: "user/pwd/email/code",
            dataType: "json",
            headers:{"Authorization": "Bearer "+ localStorage.getItem("login_user_token")},
            success: function (result) {
                if (result.code == 0) {
                    layer.msg("验证码已发送至您的邮箱", {icon: 6});
                } else {
                    layer.msg(result.msg, {icon: 5});
                }
            }
        });
    };
});